Home |
| Latest | About | Random
# Answers to writing member functions for `struct Point` Some suggestions. ```cpp #include #include using namespace std; struct Point { double x, y; Point (double _x, double _y) : x(_x), y(_y) {} Point () : x(0), y(0) {} // default constructor // Member functions void print() const { cout << '(' << x << ", " << y << ')' << endl; } void update(double new_x, double new_y) { x = new_x; y = new_y; } double distance() const { return sqrt(x * x + y * y); } double distance(const Point& other) const { double dx = x - other.x; double dy = y - other.y; return sqrt(dx * dx + dy * dy); } }; int main() { Point a(3,4); // using constructor Point::Point(double, double) Point o; // default constructed Point b(1, 1); cout << a.distance() << endl; cout << a.distance(o) << endl; cout << b.distance() << endl; cout << b.distance(a) << endl; a.update(-1, -1); a.print(); return 0; } ```